package cn.sunxiansheng.intelligent.analysis.consumer;

import cn.sunxiansheng.intelligent.analysis.entity.ELKEntity;
import cn.sunxiansheng.intelligent.analysis.utils.MailUtil;
import cn.sunxiansheng.intelligent.analysis.utils.MethodCallChainUtil;
import cn.sunxiansheng.intelligent.analysis.utils.StringUtils;
import cn.sunxiansheng.openai.client.OpenAiClient;
import com.vladsch.flexmark.html.HtmlRenderer;
import com.vladsch.flexmark.parser.Parser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * Description: elk消息监听
 *
 * @Author sun
 * @Create 2025/1/1 17:17
 * @Version 1.0
 */
@Component
@Slf4j
public class ElkListener {

    @Resource
    private OpenAiClient openAiClient;

    @Resource
    private MailUtil mailUtil;

    private static final String to = "sunxiansehng@gmail.com";

    @RabbitListener(queues = "elkQueue")
    public void receive(ELKEntity message) throws Exception {
        String timestamp = message.getTimestamp();
        String logger = message.getLogger();
        String module = message.getModule();
        String throwable = message.getThrowable();
        String host = message.getHost();
        String logMessage = message.getLogMessage();

        analyze(throwable, module, timestamp, logger, host, logMessage);
    }

    public void analyze(String throwable, String module, String timestamp, String logger,
                        String host, String logMessage) throws Exception {

        List<String> methodCallChains = MethodCallChainUtil.extractMethodCallChainsFromStackTrace(
                throwable,
                "https://gitee.com/qyxinhua_0/sunrays-framework",
                module,
                "master",
                "cn.sunxiansheng");

        // 如果方法调用链为空，则直接返回
        if (methodCallChains.isEmpty()) {
            sendMailWithDetails("线上报错（无AI分析）", "无", timestamp, logger, module, host, logMessage, throwable);
            log.info("方法调用链为空，无法分析问题");
            return;
        }

        String pattern = "        问题: 在这里总结一个问题标题\n" +
                "        ----------------------------------------\n" +
                "        1. 问题产生原因：\n" +
                "           在这里写原因\n" +
                "        ----------------------------------------\n" +
                "        2. 问题解决方式：\n" +
                "           在这里写解决方式\n" +
                "        ----------------------------------------\n";

        String info = String.format("方法调用链：%s 异常信息：%s",
                StringUtils.mergeAndTruncateWithEllipsis(methodCallChains, 500),
                StringUtils.truncateWithEllipsis(throwable, 500)
        );

        String question = String.format(
                "我会给你我的方法调用链以及异常信息：\n%s\n" +
                        "请帮我按照下面的格式去分析一下问题产生的原因和解决方式：\n%s",
                info,
                pattern
        );

        log.info("问题：{}", question);
        String aiAns = openAiClient.askAI("gpt-4o", question, false);

        log.info("AI回答：{}", aiAns);

        // 发送AI分析邮件
        sendMailWithDetails("线上报错（有AI分析）", aiAns, timestamp, logger, module, host, logMessage, throwable);
    }

    private void sendMailWithDetails(String subject, String analysisResult, String timestamp, String logger,
                                     String module, String host, String logMessage, String throwable) throws Exception {
        // 构建邮件的HTML格式内容
        String htmlContent = buildHtmlContent(subject, analysisResult, timestamp, logger, module, host, logMessage, throwable);

        // 发送邮件
        mailUtil.sendHtmlMessage(to, "SunRays-Framework", subject, htmlContent);
    }

    public String buildHtmlContent(String subject, String analysisResult, String timestamp, String logger,
                                   String module, String host, String logMessage, String throwable) {
        // 使用 Flexmark 将 analysisResult 转换为 HTML
        Parser parser = Parser.builder().build();
        HtmlRenderer renderer = HtmlRenderer.builder().build();
        String analysisHtml = renderer.render(parser.parse(analysisResult));

        // 构建 HTML 内容
        return "<html><body>" +
                "<h2>" + subject + "</h2>" +
                "<table border='1' cellpadding='10' cellspacing='0'>" +
                "<tr><td><strong>时间戳</strong></td><td>" + timestamp + "</td></tr>" +
                "<tr><td><strong>日志器</strong></td><td>" + logger + "</td></tr>" +
                "<tr><td><strong>模块</strong></td><td>" + module + "</td></tr>" +
                "<tr><td><strong>主机</strong></td><td>" + host + "</td></tr>" +
                "<tr><td><strong>日志信息</strong></td><td>" + logMessage + "</td></tr>" +
                "<tr><td><strong>异常信息</strong></td><td><pre>" + throwable + "</pre></td></tr>" +
                "</table>" +
                "<h3>AI分析结果：</h3>" +
                "<div>" + analysisHtml + "</div>" +  // 渲染后的分析结果
                "</body></html>";
    }
}
